//
//  ADJgCustomAdapterGDTSplashAd.m
//  ADJgSDKDemo-iOS
//
//  Created by Suancai on 2023/3/6.
//  Copyright © 2023 陈坤. All rights reserved.
//

#import "ADJgCustomAdapterGDTBiddingSplashAd.h"
#import <GDTMobSDK/GDTSplashAd.h>

@interface ADJgCustomAdapterGDTBiddingSplashAd()<GDTSplashAdDelegate>

@property (nonatomic, assign) bool isLoadSuccess;/**< 加载是否成功，该字段是为了处理gdt的失败回调 */

@property (nonatomic, strong) ADJgCustomAdapterSplashRequestContext *context;
@property (nonatomic, strong) GDTSplashAd *splashAd;

@end

@implementation ADJgCustomAdapterGDTBiddingSplashAd

+ (void)load {
    [self registPlatformAdLoaderClass:self forSdkName:@"gdt"];
}

/// 请求
- (void)requestAdWithContext:(ADJgCustomAdapterSplashRequestContext *)context{
    _context = context;
    [self request:context];
}

/// !!!: 竞价：询价请求
- (void)biddingRequestWithContext:(ADJgCustomAdapterSplashRequestContext *)context{
    _context = context;
    [self request:context];
}

/// !!!: 竞价：竞价结果，该方法内实现仅处理三方广告竞价结果上报即可
- (void)biddingResult:(ADJgSDKSourceBiddingResult)result AllPrice:(NSArray *)allPrices{
    // 获取一价二价
    NSNumber *winnerPrice = 0;
    NSNumber *secondPrice = 0;
    if (allPrices.count > 0) {
        NSNumber *firstPrice = allPrices.firstObject;
        // 聚合平台存储为单位为：分，GDT 是以元返回，同时也需要已元上报
        winnerPrice = [NSNumber numberWithFloat:firstPrice.floatValue * 100];
    }
    if (allPrices.count > 1) {
      NSNumber *tempSecondPrice = allPrices[1];
      secondPrice = [NSNumber numberWithFloat:tempSecondPrice.floatValue * 100];
    }
    switch (result) {
        case ADJgSDKSourceBiddingResult_Sucess:
            [self sendWinNotificationWithWinnerPrice:[NSNumber numberWithInteger:_splashAd.eCPM] withSecondPrice:secondPrice];
            break;
        case ADJgSDKSourceBiddingResult_Failed:
            [self sendLossNotificationWithPrice:winnerPrice withRease:GDTAdBiddingLossReasonLowPrice withWinnerAdnID:@""];
            break;
        case ADJgSDKSourceBiddingResult_Timeout:
            [self sendLossNotificationWithPrice:@0 withRease:GDTAdBiddingLossReasonNoAd withWinnerAdnID:@""];
            break;
        default:
            [self sendLossNotificationWithPrice:@0 withRease:GDTAdBiddingLossReasonOther withWinnerAdnID:@""];
            break;
    }
}

/// 展示
- (void)customAdapter_onAdReceive{
    [_splashAd showAdInWindow:_context.window withBottomView:_context.bottomView skipView:nil];
}


// MARK: - Method

- (void)request:(ADJgCustomAdapterSplashRequestContext *)context{
    if (!_splashAd) {
        _splashAd = [[GDTSplashAd alloc] initWithPlacementId:context.posId];
        _splashAd.delegate = self;
    }
    [_splashAd loadAd];
}

/** 竞赢上报
 *  infoDic 字典类型，支持的key有
 *  GDT_M_W_E_COST_PRICE：竞胜价格 (单位: 分)，值类型为NSNumber *
 *  GDT_M_W_H_LOSS_PRICE：最高失败出价，值类型为NSNumber *
 */
- (void)sendWinNotificationWithWinnerPrice:(NSNumber *)winnerPrice withSecondPrice:(NSNumber *)secondPrice{
    if(winnerPrice == nil){
        return ;
    }
    
    NSMutableDictionary *infoDic = [NSMutableDictionary dictionary];
    
    [infoDic setValue:winnerPrice forKey:GDT_M_W_E_COST_PRICE];
    if (secondPrice != nil) {
        [infoDic setValue:secondPrice forKey:GDT_M_W_H_LOSS_PRICE];
    }else{
        [infoDic setValue:@(0) forKey:GDT_M_W_H_LOSS_PRICE];
    }
    [_splashAd sendWinNotificationWithInfo:infoDic.copy];
}
/**
 *  竞败之后或未参竞调用
 *
 *  infoDic 竞败信息，字典类型，支持的key有
 *  GDT_M_L_WIN_PRICE ：竞胜价格 (单位: 分)，值类型为NSNumber *，选填
 *  GDT_M_L_LOSS_REASON ：优量汇广告竞败原因，竞败原因参考枚举GDTAdBiddingLossReason中的定义，值类型为NSNumber *，必填
 *  GDT_M_ADNID  ：竞胜方渠道ID，值类型为NSString *，必填
 */
- (void)sendLossNotificationWithPrice:(NSNumber *)price withRease:(GDTAdBiddingLossReason)reason withWinnerAdnID:(NSString *)winnerAdnID{
    NSMutableDictionary *infoDic = [NSMutableDictionary dictionary];
    [infoDic setValue:price forKey:GDT_M_L_WIN_PRICE];
    [infoDic setValue:@(reason) forKey:GDT_M_L_LOSS_REASON];
    [infoDic setValue:winnerAdnID forKey:GDT_M_ADNID];
    [_splashAd sendLossNotificationWithInfo:infoDic.copy];
}



// MARK: - GDTSplashAdDelegate

- (void)splashAdSuccessPresentScreen:(GDTSplashAd *)splashAd {
    [self trackSplashAdSuccessToPresent];
}

- (void)splashAdDidLoad:(GDTSplashAd *)splashAd {
    _isLoadSuccess = YES;
    NSInteger price = _splashAd.eCPM;
    [self trackSplashAdSucceed:price/100.00];
}

- (void)splashAdFailToPresent:(GDTSplashAd *)splashAd withError:(NSError *)error {
    // gdt 的失败回调特殊处理，加载成功之后调用失败，则说明广告数据加载成功，可能是present失败，所以属于展示失败，展示失败直接返回失败
    if(_isLoadSuccess) {
        [self trackSplashAdFailedToPresentWithError:error];
    // 直接失败，说明广告数据加载失败，属于请求失败么，请求失败轮询下一个平台
    } else {
        [self trackSplashAdFailedWithError:error];
    }
}

// 跳转其他页面也当作关闭处理
- (void)splashAdApplicationWillEnterBackground:(GDTSplashAd *)splashAd {
    [self splashAdClosed:splashAd];
}

- (void)splashAdExposured:(GDTSplashAd *)splashAd {
    [self trackSplashAdDisplay];
}

- (void)splashAdClicked:(GDTSplashAd *)splashAd {
    [self trackSplashAdClicked];
}

- (void)splashAdClosed:(GDTSplashAd *)splashAd {
    [self trackSplashAdClosed];
}

- (void)splashAdDidDismissFullScreenModal:(GDTSplashAd *)splashAd {
    [self trackSplashAdLandingPageClosed];
}

@end
